<template>
  <div class="system-menu-dialog-container">
    <el-dialog
      :title="state.dialog.title"
      v-model="state.dialog.isShowDialog"
      width="769px"
      class="custom-dialog"
    >
      <el-form
        ref="menuFormRef"
        :rules="rules"
        :model="ruleForm"
        label-width="80px"
        style="min-height: 50vh"
        class="ml10 mr10"
      >
        <el-row :gutter="35">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb10">
            <el-form-item label="上级菜单">
              <el-cascader
                :options="menuData"
                :props="{ checkStrictly: true, value: 'id', label: 'title' }"
                placeholder="请选择上级菜单"
                clearable
                class="w100"
                v-model="menuSuperior"
                @change="onCascadeChange"
              >
                <template #default="{ node, data }">
                  <span>{{ data.title }}</span>
                  <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb10">
            <el-form-item label="菜单类型">
              <el-radio-group v-model="menuType">
                <el-radio-button value="menu">菜单</el-radio-button>
                <el-radio-button value="action">操作</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <template v-if="menuType === 'menu'">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
              <el-form-item label="菜单名称" required prop="title">
                <el-input
                  v-model="ruleForm.title"
                  placeholder="中文或国际化：message.router.xxx"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
              <el-form-item label="路由名称" required prop="name">
                <el-input
                  v-model="ruleForm.name"
                  placeholder="路由中的name（英文名）"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
              <el-form-item label="路由路径" required prop="path">
                <el-input
                  v-model="ruleForm.path"
                  placeholder="路由中的 path 值"
                  clearable
                  @input="onInputPath"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
              <el-form-item label="重定向">
                <el-input
                  v-model="ruleForm.redirect"
                  placeholder="请输入路由重定向"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
              <el-form-item label="菜单图标">
                <IconSelector placeholder="请输入菜单图标" v-model="ruleForm.meta.icon" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
              <el-form-item label="菜单排序">
                <el-input-number
                  v-model="ruleForm.idx"
                  controls-position="right"
                  placeholder="请输入排序"
                  class="w100"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
              <el-form-item
                label="组件路径"
                :required="!ruleForm.meta.isIframe && !state.isLink"
                prop="component"
              >
                <!--                <el-input-->
                <!--                  v-model="ruleForm.component"-->
                <!--                  :disabled="ruleForm.meta.isIframe || state.isLink"-->
                <!--                  placeholder="组件路径(去掉@/view后的路径带.vue后缀)"-->
                <!--                  clearable-->
                <!--                ></el-input>-->
                <el-autocomplete
                  style="width: 100%"
                  v-model="ruleForm.component"
                  :fetch-suggestions="fetchComponents"
                  :disabled="ruleForm.meta.isIframe || state.isLink"
                  clearable
                  placeholder="组件路径(去掉@/view后的路径带.vue后缀)"
                >
                  <template #default="{ item }">
                    <div class="value">
                      <span :class="{ 'text-through': item.tips }"
                        >{{ item.value }}（{{ item.description }}）</span
                      >
                      <span class="ml5 font12 color-warning" v-if="item.tips">{{ item.tips }}</span>
                      <span class="ml5 font12 color-danger" v-if="item.new">新</span>
                    </div>
                  </template>
                </el-autocomplete>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
              <el-form-item label="流程图" prop="wf_design_id">
                <el-select
                  v-model="ruleForm.wf_design_id"
                  placeholder="关联流程图"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="(item, index) in wfItems"
                    :key="index"
                    :value="item.id"
                    :label="item.name"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
              <el-form-item label="链接地址">
                <el-input
                  v-model="ruleForm.meta.isLink"
                  placeholder="外链/内嵌时链接地址（http:xxx.com）"
                  clearable
                  :disabled="!state.isLink"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <!--						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">-->
            <!--							<el-form-item label="权限标识">-->
            <!--								<el-select v-model="ruleForm.meta.roles" multiple placeholder="取角色管理" clearable class="w100">-->
            <!--									<el-option label="admin" value="admin"></el-option>-->
            <!--									<el-option label="common" value="common"></el-option>-->
            <!--								</el-select>-->
            <!--							</el-form-item>-->
            <!--						</el-col>-->
          </template>
          <template v-if="menuType === 'action'">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb10">
              <el-button type="success" :icon="Plus" @click="onAddRow" class="ml5">
                新增按钮
              </el-button>
              <el-button :icon="CirclePlus" @click="onAddDefaultRow"> 导入默认按钮</el-button>
            </el-col>

            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb10">
              <div
                v-for="(element, index) in ruleForm.actions"
                :key="index"
                class="table-group ml5 mr5"
              >
                <div
                  class="flex-grow mb5 mr1"
                  style="border-bottom: 1px solid var(--el-color-primary-light-9)"
                >
                  <div class="mb5 flex-grow">
                    <span class="flex-shrink">名称:</span>
                    <el-input
                      v-model="element.name"
                      placeholder="名称"
                      class="ml5"
                      style="width: 120px"
                    />
                    <span class="flex-shrink ml5">唯一值:</span>
                    <!--                    <el-input v-model="element.action" :disabled="sysActions.includes(element.action)"-->
                    <!--                              placeholder="ID" class="ml5"/>-->
                    <el-autocomplete
                      v-model="element.action"
                      :disabled="sysActions.includes(element.action)"
                      :fetch-suggestions="fetchActions"
                      class="ml5 flex-shrink"
                      clearable
                      placeholder="唯一值"
                      style="width: 200px"
                      @select="onActionSelect($event, element)"
                    >
                      <template #default="{ item }">
                        <div class="value">
                          {{ item.action }}（{{ item.name }} - {{ item.description }}）
                        </div>
                      </template>
                    </el-autocomplete>
                    <!--                        <span class="flex-shrink ml5">组件:</span>-->
                    <!--                        <el-input v-model="element.component" placeholder="组件" class="ml5"/>-->
                    <span class="flex-shrink ml5">样式:</span>
                    <el-select
                      v-model="element.type"
                      class="ml5 flex-shrink"
                      placeholder="样式"
                      style="width: 100px"
                    >
                      <el-option label="Default" value="default" />
                      <el-option label="Primary" value="primary" />
                      <el-option label="Warning" value="warning" />
                      <el-option label="Danger" value="danger" />
                      <el-option label="Success" value="success" />
                      <el-option label="Info" value="info" />
                    </el-select>
                    <el-button @click="setDefaultJson(element)" type="warning" class="ml5">
                      设置默认参数
                    </el-button>
                  </div>
                  <div class="flex align-center flex-warp pr5 pl5">
                    <span class="flex-shrink">位置:</span>
                    <el-switch
                      v-model="element.global"
                      class="ml5"
                      inline-prompt
                      active-text="表格顶部"
                      inactive-text="表格顶部"
                    />
                    <div class="ml-auto">
                      <el-radio-group v-if="onRadioGroup(element)" v-model="element.model">
                        <el-radio value="">无</el-radio>
                        <el-radio value="trigger">勾选</el-radio>
                        <el-radio value="request">请求</el-radio>
                        <el-radio value="download">下载</el-radio>
                        <el-radio value="business">业务</el-radio>
                        <el-radio value="form">表单</el-radio>
                        <!--                        <el-radio value="selector">选择器</el-radio>-->
                      </el-radio-group>
                      <el-button
                        :disabled="index <= 0"
                        circle
                        :icon="Top"
                        @click.stop="onSplice(-1, index)"
                      />
                      <el-button
                        :disabled="index >= (ruleForm.actions?.length || 0) - 1"
                        circle
                        :icon="Bottom"
                        @click.stop="onSplice(1, index)"
                      />
                      <el-button type="danger" :icon="Delete" circle @click="onDelRow(index)" />
                    </div>
                  </div>
                  <div v-if="['trigger', 'request'].includes(element.model || '') || ['ExportWord'].includes(element.action)">
                    <span class="mr5">接口:</span>
                    <el-input
                      v-model="element.api"
                      style="width: 200px"
                      placeholder="接口地址API"
                    />
                    <span class="flex-shrink ml5">方法:</span>
                    <el-select
                      v-model="element.method"
                      class="ml5"
                      clearable
                      placeholder="方法"
                      style="width: 200px"
                    >
                      <el-option label="GET" value="get" />
                      <el-option label="POST" value="post" />
                      <el-option label="PUT" value="put" />
                      <el-option label="DELETE" value="delete" />
                    </el-select>
                    <el-checkbox
                      v-model="element.confirm"
                      label="确认弹窗"
                      class="ml10"
                    ></el-checkbox>
                  </div>
                  <div v-if="element.model === 'download'" class="mt5">
                    <el-upload
                      type="warning"
                      :auto-upload="false"
                      :show-file-list="false"
                      @change="onFileChange($event, element)"
                    >
                      <template #trigger>
                        <el-button type="primary" :icon="UploadFilled" plain>上传附件/word模板</el-button>
                        <span class="ml10">{{ element.default_value_parse['fileName'] }}</span>
                      </template>
                    </el-upload>
                  </div>
                  <div v-else-if="['business', 'form', 'selector'].includes(element.model || '')">
                    <span class="flex-shrink mr5"
                      >{{ element.model === 'form' ? '表单' : '业务' }}:</span
                    >
                    <el-tree-select
                      v-model="element.business_id"
                      :data="menuData"
                      :render-after-expand="false"
                      default-expand-all
                      style="width: 240px"
                      value-key="id"
                      clearable
                      filterable
                    >
                    </el-tree-select>
                  </div>
                </div>
              </div>
              <el-empty
                v-if="!ruleForm.actions?.length"
                :image-size="50"
                description="点击按钮新增按钮"
              />
            </el-col>
          </template>
          <template v-if="menuType === 'menu'">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
              <el-form-item label="是否隐藏">
                <el-radio-group v-model="ruleForm.meta.isHide">
                  <el-radio :value="true">隐藏</el-radio>
                  <el-radio :value="false">不隐藏</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
              <el-form-item label="页面缓存">
                <el-radio-group v-model="ruleForm.meta.isKeepAlive">
                  <el-radio :value="true">缓存</el-radio>
                  <el-radio :value="false">不缓存</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
              <el-form-item label="是否固定">
                <el-radio-group v-model="ruleForm.meta.isAffix">
                  <el-radio :value="true">固定</el-radio>
                  <el-radio :value="false">不固定</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
              <el-form-item label="是否外链">
                <el-radio-group
                  v-model="state.isLink"
                  :disabled="ruleForm.meta.isIframe"
                  @change="isLinkChange"
                >
                  <el-radio :value="true">是</el-radio>
                  <el-radio :value="false">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
              <el-form-item label="是否内嵌">
                <el-radio-group v-model="ruleForm.meta.isIframe" @change="onSelectIframeChange">
                  <el-radio :value="true">是</el-radio>
                  <el-radio :value="false">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </template>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer flex align-center">
          <el-button :icon="DocumentCopy" type="info" @click="onCopy"> 复制</el-button>
          <el-button :icon="CopyDocument" type="warning" @click="onPaste" class="mr-auto">
            粘贴
          </el-button>
          <el-button @click="onCancel">取 消</el-button>
          <!--					<el-button type="warning" @click="onReset(menuFormRef)">重 置</el-button>-->
          <el-button type="primary" @click="onSubmit(menuFormRef)"
            >{{ state.dialog.submitTxt }}
          </el-button>
        </div>
      </template>
    </el-dialog>
    <JsonEditorDialog ref="editorRef" @change="onJsonChange" />
  </div>
</template>

<script setup lang="ts">
import { defineAsyncComponent, reactive, ref, unref, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import {
  copyText,
  defaultValueToString,
  pasteText,
  swapArrayElements,
  toPathCapitalize
} from '@/utils'
import { useBaseApi, useBaseFileApi } from '@/api/base'
import { ElMessage } from 'element-plus'
import {
  CopyDocument,
  DocumentCopy,
  Plus,
  CirclePlus,
  Delete,
  Top,
  Bottom,
  UploadFilled
} from '@element-plus/icons-vue'
import { clone, debounce } from 'xe-utils'
import { useWfApi } from '@/api/wf'
import { defaultActions } from '@/utils/custom'
import type { FormInstance, FormRules, UploadFile } from 'element-plus'
import type { BusinessUIAction, WorkflowDesignRow } from '@/types/custom'

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh'])

// 引入组件
const IconSelector = defineAsyncComponent(() => import('@/components/iconSelector/index.vue'))
const JsonEditorDialog = defineAsyncComponent(() => import('@/components/JsonEditorDialog.vue'))

// 定义变量内容
const sysActions = defaultActions.map((v) => v.action)
const editorRef = ref()
const menuFormRef = ref()
const { t } = useI18n()
const { EditBusiness, GetBusinessTree } = useBaseApi()
const { UploadBaseFile } = useBaseFileApi()
const { GetWorkFlowDesignList } = useWfApi()
// 表单默认数据
const ruleFormData: RouteItem = {
  id: '', // 主键
  pid: '', // 父级
  title: '', // 名称
  name: '', // 路由名称
  component: '', // 组件路径
  idx: 0, // 菜单排序
  path: '', // 路由路径
  redirect: '', // 路由重定向，有子集 children 时
  meta: {
    title: '', // 菜单名称
    icon: '', // 菜单图标
    isHide: false, // 是否隐藏
    isKeepAlive: true, // 是否缓存
    isAffix: false, // 是否固定
    isLink: '', // 外链/内嵌时链接地址（http:xxx.com），开启外链条件，`1、isLink: 链接地址不为空`
    isIframe: false // 是否内嵌，开启条件，`1、isIframe:true 2、isLink:链接地址不为空`
    // roles: '' // 权限标识，取角色管理
  },
  actions: [], // 菜单类型为按钮时，权限标识
  wf_design_id: ''
}
// 表单
const ruleForm = ref<RouteItem>(ruleFormData)
// 一些状态
const state = reactive({
  isLink: false, // 是否外链
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: ''
  }
})

const validatePath = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入路由路径（需唯一）'))
  } else if (!/^\//.test(value)) {
    callback(new Error('路由路径必须以“/”开头'))
  } else {
    callback()
  }
}

// 错误验证
const rules = reactive<FormRules<RouteItem>>({
  name: [{ required: true, message: '请输入路name值', trigger: 'blur' }],
  title: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  component: [{ required: true, message: '请输入组件路径', trigger: 'blur' }],
  path: [{ required: true, validator: validatePath, trigger: 'blur' }]
})
// 切换栏
const menuType = ref<string>('menu')
// 上级菜单
const menuSuperior = ref<string[] | string | undefined>()
// 上级菜单数据
const menuData = ref<RouteItems>([])
// 流程图
const wfItems = ref<WorkflowDesignRow[]>([])

// 自动生成路由唯一值
const onInputPath = debounce<string>((value) => {
  if (value) {
    ruleForm.value.name = toPathCapitalize(value)
  }
}, 500)

/**
 * 默认模板
 * @param queryString
 * @param cb
 */
const fetchComponents = (queryString: string, cb: any) => {
  // const results = queryString
  cb([
    { value: '/layout/routerView/LayoutParent', description: '全局容器: 为父组件时的容器' },
    // {
    //   value: '/components/TemplateTable.vue',
    //   description: '《表格》模板',
    //   tips: '即将废弃请使用 TemplateGrid'
    // },
    { value: '/components/grid/TemplateGrid.vue', description: '表格模板', new: true },
    { value: '/components/grid/TemplateGridGroup.vue', description: '表格组模板', new: true },
    { value: '/components/form/components/TemplateFormContent.vue', description: '表单模板' },
    { value: '/layout/routerView/iframes.vue', description: '内嵌iframe' },
    { value: '/layout/routerView/link.vue', description: '外链' }
  ])
}

/**
 * 默认按钮唯一值
 * @param queryString
 * @param cb
 */
const fetchActions = (queryString: string, cb: any) => {
  // const results = queryString
  cb(defaultActions.map((v) => ({ ...v, value: v.action })))
}

/**
 * 排序
 * @param diff
 * @param index
 */
const onSplice = (diff: number, index: number) => {
  swapArrayElements(ruleForm.value.actions || [], index, index + diff)
}

// 新增行
const onAddRow = () => {
  ruleForm.value.actions?.push({
    action: '',
    name: '',
    global: false,
    visible: false,
    idx: ruleForm.value.actions?.length || 0,
    api: '',
    method: '',
    component: '',
    default_value: '',
    default_value_parse: {},
    set_json: '',
    set_json_parse: {}
  })
}
// 新增
const onAddDefaultRow = () => {
  defaultActions
    .filter((f) => f.defaultValue)
    .forEach((v) => {
      if (!ruleForm.value.actions?.some((s) => s.action === v.action)) {
        ruleForm.value.actions?.push(clone(v, true))
      }
    })
}
// 删除行
const onDelRow = (k: number) => {
  ruleForm.value.actions?.splice(k, 1)
}
/**
 * 菜单赋值 el-cascader 所使用的 title 属性
 * @param routes
 */
const getMenuData = (routes: RouteItems) => {
  const arr: RouteItems = []
  routes.map((val: RouteItem) => {
    if (val.meta?.title) {
      val['title'] = t(val.meta?.title)
    } else {
      val['title'] = String(val.name || val.id)
    }
    val['label'] = val['title']
    arr.push({ ...val })
    if (val.children) getMenuData(val.children)
  })
  return arr
}

/**
 * 获取工作流列表
 */
const initGridData = () => {
  GetWorkFlowDesignList().then(({ data }) => {
    wfItems.value = data
  })
}

// 打开弹窗
const openDialog = (type: string, row?: any) => {
  if (type === 'edit') {
    // 模拟数据，实际请走接口
    menuType.value = 'menu'
    // row.idx = Math.floor(Math.random() * 100);
    state.isLink = !!row.meta.isLink
    ruleForm.value = JSON.parse(JSON.stringify(row))
    ruleForm.value.title = ruleForm.value.meta.title
    state.dialog.title = '修改菜单'
    state.dialog.submitTxt = '修 改'
  } else {
    state.dialog.title = '新增菜单'
    state.dialog.submitTxt = '新 增'
    state.isLink = false
    Object.assign(ruleForm.value, clone(ruleFormData, true))
    ruleForm.value.actions = []
    ruleForm.value.pid = row ? row.pid : ''
    ruleForm.value.path = row ? row.path : ''
  }
  state.dialog.type = type
  state.dialog.isShowDialog = true
  menuSuperior.value = ruleForm.value.pid
  if (!menuData.value.length) {
    GetBusinessTree().then(({ data }) => {
      menuData.value = getMenuData(data)
    })
  }
  nextTick(() => {
    if (menuFormRef.value) onReset(menuFormRef.value)
  })

  initGridData()
}

// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false
}
// 取消
const onCancel = () => {
  closeDialog()
}
// 复制
const onCopy = () => {
  const menu = unref(ruleForm)
  const option = {
    component: menu.component,
    meta: { ...menu.meta },
    name: menu.name,
    idx: menu.idx,
    redirect: menu.redirect,
    path: menu.path,
    title: menu.title
  }
  copyText(JSON.stringify(option))
    .then(() => {
      ElMessage.success('复制成功')
    })
    .catch(() => {
      ElMessage.success('复制失败')
    })
}
// 复制
const onPaste = () => {
  try {
    pasteText()
      .then((str) => {
        if (str) {
          const menu = JSON.parse(str)
          ruleForm.value.component = menu.component
          ruleForm.value.meta = menu.meta
          ruleForm.value.name = menu.name || ''
          ruleForm.value.redirect = menu.redirect || ''
          ruleForm.value.path = menu.path
          ruleForm.value.idx = menu.idx || 0
          ruleForm.value.title = menu.title || ''
          console.log(menu)
        }
      })
      .catch(() => {
        ElMessage.success('粘贴失败')
      })
  } catch (e) {
    ElMessage.warning('粘贴失败')
  }
  // const menu = unref(ruleForm)
  // const option = {
  //   component: menu.component,
  //   meta: { ...menu.meta },
  //   name: menu.name,
  //   redirect: menu.redirect,
  //   path: menu.path,
  //   title: menu.title
  // }
  // copyText(JSON.stringify(option)).then(() => {
  //   ElMessage.success('复制成功')
  // })
}

// 重置
const onReset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.clearValidate()
}
// 提交
const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      ruleForm.value.meta.title = ruleForm.value.title
      ruleForm.value.actions = ruleForm.value.actions?.map((v, index) => {
        v.idx = index
        defaultValueToString(v, 'default_value')
        return v
      })
      EditBusiness(ruleForm.value).then(() => {
        closeDialog() // 关闭弹窗
        emit('refresh')
      })
    }
  })

  // if (state.dialog.type === 'add') { }
  // setBackEndControlRefreshRoutes() // 刷新菜单，未进行后端接口测试
}

/**
 * 设置按钮默认参数
 * @param element
 */
let editElement: RouteActionItem | null = null
const setDefaultJson = (element: RouteActionItem) => {
  editElement = element
  editorRef.value.open(element.default_value_parse || {})
}

/**
 * 修改默认参数
 * @param value
 */
const onJsonChange = (value: TypedAny) => {
  if (editElement) {
    editElement.default_value_parse = value
  }
}

/**
 * 选择父级
 * @param value
 */
const onCascadeChange = (value: string[]) => {
  if (value && value.length) {
    ruleForm.value.pid = value[value.length - 1]
  } else {
    ruleForm.value.pid = ''
  }
}

/**
 * 上传文件
 * @param file
 * @param element
 */
const onFileChange = (file: UploadFile, element: RouteActionItem) => {
  UploadBaseFile(file).then(({ data }) => {
    if (data && data.length) {
      if (!element.default_value_parse) element.default_value_parse = {}
      element.default_value_parse['downFileId'] = data[0].id
      element.default_value_parse['fileName'] = data[0].fileName
      ElMessage.success('文件上传成功')
    }
  })
}

/**
 * 选择按钮
 * @param option
 * @param element
 */
const onActionSelect = (option: BusinessUIAction, element: RouteActionItem) => {
  for (const key in option) {
    // @ts-ignore
    const value: any = option[key] || element[key]
    // @ts-ignore
    if (value) element[key] = value
  }
}

let component = ''

const isLinkChange = () => {
  if (state.isLink) {
    if (ruleForm.value.component) component = ruleForm.value.component
    else component = ''
    ruleForm.value.component = '/layout/routerView/link.vue'
  } else {
    if (component) ruleForm.value.component = component
  }
}
// 是否内嵌下拉改变
const onSelectIframeChange = () => {
  if (ruleForm.value.meta.isIframe) {
    state.isLink = true
    if (ruleForm.value.component) component = ruleForm.value.component
    else component = ''
    ruleForm.value.component = '/layout/routerView/iframes.vue'
  } else {
    state.isLink = !!ruleForm.value.meta.isLink
    isLinkChange()
  }
}

const onRadioGroup = (element: RouteActionItem) => {
  return (
    (element.model === 'request' || !sysActions.includes(element.action)) &&
    element.action !== 'Print'
  )
}

// 暴露变量
defineExpose({
  openDialog
})
</script>
